package com.puyuba.puyuba.view.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.hjq.toast.ToastUtils;
import com.puyuba.puyuba.R;
import com.pyb.java.basemodule.BaseFragment;
import com.puyuba.puyuba.utils.MyJavascriptInterface;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.bean.UserInfoBean;
import com.puyuba.puyuba.network.BaseApis;
import com.pyb.java.commonutil.ToastHelper;

import com.pyb.java.commonutil.utils.StatusBarUtil;
import com.pyb.java.commonutil.widgets.X5WebView;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;

public class WebviewFragmentFind extends BaseFragment {

    private X5WebView regisetWv;
    private WebSettings webSettings;
    String referer = BaseApis.API_BASE_URL;
    boolean firstVisitWXH5PayUrl = true;
    String return_url = "";
    boolean isToPay;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_webview_5;
    }

    @Override
    protected void initView() {
        View viewStatusBar = (View) getActivity().findViewById(R.id.view_status_bar1);
        int screenHeight = StatusBarUtil.getStatusBarHeight(getContext());
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewStatusBar.getLayoutParams();
        layoutParams.height = screenHeight;
        viewStatusBar.setLayoutParams(layoutParams);
        regisetWv   = new X5WebView(getContext(), null);
        if (regisetWv.getX5WebViewExtension() != null) {
            Bundle data = new Bundle();

            data.putBoolean("standardFullScreen", false);// true表示标准全屏，会调起onShowCustomView()，false表示X5全屏；不设置默认false，

            data.putBoolean("supportLiteWnd", false);// false：关闭小窗；true：开启小窗；不设置默认true，

            data.putInt("DefaultVideoScreen", 2);// 1：以页面内开始播放，2：以全屏开始播放；不设置默认：1

            regisetWv.getX5WebViewExtension().invokeMiscMethod("setVideoParams",
                    data);
            Bundle data2 = new Bundle();

            //val为true或false。  实现自动播放
            data2.putBoolean("require", true);
            regisetWv.getX5WebViewExtension().invokeMiscMethod("setVideoPlaybackRequiresUserGesture", data2);
        }

        initevent();

    }

    public static WebviewFragmentFind getInstance(String type) {
        WebviewFragmentFind webviewFragment = new WebviewFragmentFind();
        Bundle args = new Bundle();
        args.putString("url", type);
        webviewFragment.setArguments(args);
        return webviewFragment;
    }

    private void initevent(){
        regisetWv.removeJavascriptInterface("searchBoxJavaBridge_");
        regisetWv.removeJavascriptInterface("accessibility");
        regisetWv.removeJavascriptInterface("accessibilityTraversal");
        LinearLayout llParent = getActivity().findViewById(R.id.ll_parent5);
        llParent.addView(regisetWv, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));

        com.tencent.smtt.sdk.WebSettings setting = regisetWv.getSettings();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            setting.setMixedContentMode(1);
        }
        setting.setJavaScriptEnabled(true);
        //将图片调整到适合webview的大小
        setting.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        setting.setLoadWithOverviewMode(true);
//        // 是否支持画面缩放，默认不支持
//        setting.setBuiltInZoomControls(true);
//        setting.setSupportZoom(true);
//        // 是否显示缩放图标，默认显示
//        setting.setDisplayZoomControls(false);
        // 设置网页内容自适应屏幕大小
        setting.setLayoutAlgorithm(com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setJavaScriptCanOpenWindowsAutomatically(true);
        setting.setDomStorageEnabled(true);
        setting.setCacheMode(com.tencent.smtt.sdk.WebSettings.LOAD_NO_CACHE);
        setting.setAllowFileAccess(false);
        setting.setAllowFileAccessFromFileURLs(false);
        setting.setAllowUniversalAccessFromFileURLs(false);

        try {
            setting.setUserAgentString(regisetWv.getSettings().getUserAgentString() + "/pybapp/"+getVersionName());
        } catch (Exception e) {
            e.printStackTrace();
        }
//        regisetWv.addJavascriptInterface(this,"android");
        regisetWv.addJavascriptInterface(new MyJavascriptInterface(getActivity()),"android");
        WebStorage.getInstance().deleteAllData();//清空H5保存在本地的所有内容
        regisetWv.setLongClickable(true);
        registerForContextMenu(regisetWv);
        regisetWv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                subString(url, "return_url=");
                subString(url, "redirect_url=");

                if (url.startsWith("weixin://wap/pay?") || url.startsWith("wechat")) {
                    try {
                        isToPay = true;
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } catch (Exception e) {
                        // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                        ToastHelper.show("该设备没有安装微信");
                        return true;
                    }
                } else if (url.startsWith("alipays://") || url.startsWith("alipay")) {
                    try {
                        isToPay = true;
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } catch (Exception e) {
                        // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                        // 启动支付宝 App 失败，会自行跳转支付宝网页支付
                        return true;
                    }
                }

                // 处理微信 H5 支付跳转时验证请求头 referer 失效
                // 验证不通过会出现“商家参数格式有误，请联系商家解决”
                if (url.contains("wx.tenpay.com")) {

                    // 兼容 Android 4.4.3 和 4.4.4 两个系统版本设置 referer 无效的问题
                    if (("4.4.3".equals(Build.VERSION.RELEASE))
                            || ("4.4.4".equals(Build.VERSION.RELEASE))) {
                        if (firstVisitWXH5PayUrl) {
                            view.loadDataWithBaseURL(referer, "<script>window.location.href=\"" + url + "\";</script>",
                                    "text/html", "utf-8", null);
                            // 修改标记位状态，避免循环调用
                            // 再次进入微信H5支付流程时记得重置状态 firstVisitWXH5PayUrl = true
                            firstVisitWXH5PayUrl = false;
                        }
                        // 返回 false 由系统 WebView 自己处理该 url
                        return false;
                    } else {
                        // HashMap 指定容量初始化，避免不必要的内存消耗
                        HashMap<String, String> map = new HashMap<>(1);
                        map.put("Referer", referer);
                        view.loadUrl(url, map);
                        return true;
                    }
                } else {
//                    view.loadUrl(url);
//                    return true;
                    return super.shouldOverrideUrlLoading(view,url);
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                // 不要调用super.onReceivedSslError，因为其包含了一条 handler.cancel()，第一次访问时无法加载，第二次以后可以加载
                // super.onReceivedSslError(view, handler, error);
                // 忽略SSL证书错误，继续加载页面
                handler.proceed();
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {//是否是为 main frame创建
                    webView.loadUrl("about:blank");// 避免出现默认的错误界面
//                    llNetworkFailed.setVisibility(View.VISIBLE);
                }
            }
        });
        String url = getArguments().getString("url");
        regisetWv.loadUrl(url);
        regisetWv.setWebChromeClient(new MyChromeWebClient());
    }

    /** 视频全屏参数 */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private IX5WebChromeClient.CustomViewCallback customViewCallback;
    /** 视频播放全屏 **/
    private void showCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        ((Activity)getContext()).getWindow().getDecorView();

        FrameLayout decor = (FrameLayout)  ((Activity)getContext()).getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(getContext());
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /** 隐藏视频全屏 */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        FrameLayout decor = (FrameLayout) ((Activity)getContext()).getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        regisetWv.setVisibility(View.VISIBLE);
        setStatusBarVisibility(true);
    }
    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        ((Activity)getContext()).getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    /** 全屏容器界面 */
    static class FullscreenHolder extends FrameLayout {

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }
    }
    public class MyChromeWebClient extends WebChromeClient {
        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
            super.onShowCustomView(view, customViewCallback);
            showCustomView(view,customViewCallback);
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
            hideCustomView();
        }

    }
    private String getVersionName()throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getContext().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(getContext().getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo.versionName;
    }

    private void subString(String url, String target) {
        if (url.contains(target)) {
            String substring = url.substring(url.indexOf(target) + target.length(), url.length());
            if (substring.contains("&")) {
                String ss = substring.substring(0, substring.indexOf("&"));
                return_url = Uri.decode(ss);
            } else {
                return_url = Uri.decode(substring);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isToPay && !TextUtils.isEmpty(return_url)) {
            regisetWv.loadUrl(return_url);
            return_url = "";
            isToPay = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        regisetWv.destroy();
        Log.i("inffs", "onDestroy");
    }
}
